package com.bwie.bargain.listen;

import com.bwie.bargain.dao.BargainDao;
import com.bwie.bargain.dao.BarorderDao;
import com.bwie.bargain.entity.BargainEntity;
import com.bwie.bargain.entity.BarorderEntity;
import com.bwie.bargain.feign.GoodsFeign;
import com.bwie.bargain.vo.GoodsVo;
import com.bwie.bargain.vo.IdVo;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Date;
import java.util.Random;

@Component
public class BarorderListener {

    @Autowired
    private BargainDao orderDao;
    @Autowired
    private GoodsFeign goodsFeign;
    @Autowired
    private BarorderDao barorderDao;
    @RabbitListener(queues = "orders2")
    @RabbitHandler
    public void addOrders2(IdVo idVo, Message message, Channel channel) throws IOException {
        // 根据活动id获取活动详情
        BarorderEntity orderEntity = new BarorderEntity();
        BargainEntity bargainEntity = orderDao.selectById(idVo.getActivityId());

        //feign调用 根据商品id获取商品信息
        GoodsVo goodsVo = goodsFeign.info2(bargainEntity.getGoodsId());

        orderEntity.setUserId(idVo.getUserId());//用户id
        orderEntity.setGoodsId(goodsVo.getGid());//商品id
        orderEntity.setActivityId(idVo.getActivityId());//活动id
        orderEntity.setGoodsName(goodsVo.getGoodsName());//商品名称
        orderEntity.setGoodsCount(1);//商品数量 默认为1件
        orderEntity.setGoodsPrice(bargainEntity.getGoodsPrice());//商品原价
        orderEntity.setGoodsChannel(2);//1.pc 2.android 3.ios 默认为安卓
        orderEntity.setStatus(0);//订单状态：0新建未支付，1已支付，2已发货，3已收货，4已退款，5已完成
        orderEntity.setCreateDate(new Date());//订单创建时间
        //随机数
        String code = "";
        Random random = new Random();
        for(int i = 0; i<10;i++){
            code+= random.nextInt(10);
        }
        orderEntity.setOrderno(code+"ZHIZHI");//生成订单编号 防止付款时订单重复
        System.out.println("生成订单成功");
        //添加订单
        barorderDao.insert(orderEntity);
        //手动确认 防止消息丢失
        channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
    }
}
